<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90" v-if="hasFind")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled" @on-change="listenCall(item.fn, item.model, $event)")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.label"
                  :key="index"
                ) {{ c_item.value }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.label"
                  :key="index"
                ) {{ c_item.value }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable :disabled="item.isDisabled")
            template(v-if="item.type === 'radio'")
              RadioGroup.beautiful-radio-group(type="button" v-model="formData[item.model]")
                Radio.display-inline-block(v-for="c_item of item.radioArr" :label="c_item.value") {{c_item.label}}
            template(v-if="item.type === 'button'")
              Button.search-btn(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
        @on-selection-change="tableSelectChange"
        )
          .clearfix.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
            .pull-right.table-title-btns
              Button.mr-10(type="info" @click="handleShowCreateCommercialWagesModal('create')" v-if="hasAdd") 新增
              Button.mr-10(type="info" ghost @click="handleShowTreatmentLinkManageModal" v-if="hasImport") 导入
              Button.mr-10(type="info" ghost @click="exportBtn" v-if="hasExport") 导出
              Button.mr-10(v-if="hasDelete" type="warning" @click="handleDelete(selectedIdArr.join(','))" :disabled="!selectedIdArr.length > 0") 删除
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(type="text" size="small" @click="handleShowCreateCommercialWagesModal('edit',row.id)" v-if="hasView") 编辑
            Button.mr-10(type="text" size="small" @click="handleDel(row)" v-if="hasUpdate") {{row.linkStatus == 1 ? '启用':'禁用'}}
            Button.mr-10(type="text" size="small" @click="isDeleteModal(row)" v-if="hasDelete") 删除
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )

    //- 新建弹窗
    CreateCommercialWagesModal(ref="CreateCommercialWagesModal" @query="searchFn")
    TreatmentLinkManage(ref="TreatmentLinkManageModal" :axsEnableSwitch="axsEnableSwitch" @handleMaxSizeTen="handleMaxSizeTen" @query="searchFn")
    //- 编辑环节弹窗
    //- CreateNodeModal(ref="CreateNodeModal" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { TreatmentApi } from '@/api/Treatment.api.js'
import { EnumApi } from '@/api/Enum.api.js'
import { CommercialWagesThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { TreatmentBasicsLinkApi } from '@/api/TreatmentBasicsLink.api.js'
import { TreatmentBasicsTypeApi } from '@/api/TreatmentBasicsType.api.js'
import CreateCommercialWagesModal from './modal/CreateCommercialWagesModal.vue'
import TreatmentLinkManage from './modal/treatmentLinkManageModal.vue'
// import CreateNodeModal from './modal/CreateNodeModal.vue'

export default {
  name: 'socialWagesManage', // 社保待遇管理

  components: {
    CreateCommercialWagesModal,
    TreatmentLinkManage
    // CreateNodeModal
  },

  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },
    // 查看编辑
    hasView () {
      return this.actionArr.indexOf('View') > -1
    },
    // 新增
    hasAdd () {
      return this.actionArr.indexOf('Add') > -1
    },
    // 更新
    hasUpdate () {
      return this.actionArr.indexOf('Update') > -1
    },
    // 删除
    hasDelete () {
      return this.actionArr.indexOf('Delete') > -1
    },
    // 待遇环节基础数据批量导入
    hasImport () {
      return this.actionArr.indexOf('Import') > -1
    },
    // 删除
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    }

  },

  data () {
    return {
      thead: _cloneDeep(CommercialWagesThead),
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        agentCount: 0, // 办理中
        doneCount: 0 // 办理中
      },
      selectedIdArr: [],
      formData: {
        TreatmentName: '',
        InsuredTypeId: '00000000-0000-0000-0000-000000000000',
        LinkName: '',
      },
      formItem: [
        { type: 'select', label: '参保险种：', placeholder: '请选择参保险种', prop: 'InsuredTypeId', model: 'InsuredTypeId', options: 'InsuredTypeId', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-6' },
        { type: 'input', label: '待遇名称：', placeholder: '请输入待遇名称', prop: 'TreatmentName', model: 'TreatmentName', isDisabled: false, style: 'ivu-col-span-6' },
        { type: 'input', label: '环节名称：', placeholder: '请输入环节名称', prop: 'LinkName', model: 'LinkName', isDisabled: false, style: 'ivu-col-span-6' },
        { type: 'button', isDisabled: false, style: '' }
      ],
      rules: {
        
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      arrListDown: {
        tempOps: [],
        defaultRadioArr: [{ value: '1', label: '是' }, { value: '0', label: '否' }],
        InsuredTypeId: [],
        parameterstatus: [],
        server: [],
        companyList: [],
        employeeList: [],
        treatmentParametersEnableList: []
      },
      queryEmployeeList: [],
      areaTree: [], // 中国所有城市树
      axsEnableSwitch: false,
    }
  },

  mounted () {
    this.getInsuranceTypeList()
    this.query()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    // 获取薪资导入页面数据源
    async getInsuranceTypeList () {
      let res = await TreatmentBasicsTypeApi.getInsuranceTypeList()
      console.log('获取薪资导入页面数据源res: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        for (var i in result) {
          result[i].label = result[i].value
          result[i].value =  result[i].text
        }
        this.arrListDown.InsuredTypeId = result
      }
    },

    // 获取客服
    async servers () {
      var params = {
        PageIndex: 1,
        PageSize: 100,
        Args: ''
      }
      Common.servers(params, this.arrListDown, 'server')
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过50M',
        duration: 50,
        closable: true
      })
    },

    // 获取客户下拉内容
    async getTreatmentEnjoyCustomer () {
      var params = {
        PageIndex: 1,
        PageSize: 10000
      }
      let res = await TreatmentApi.getTreatmentEnjoyCustomer(params)
      console.log('res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.companyList = res.data.data.map(item => {
          return { label: item.name, value: item.id }
        })
      }
    },

    // 获取员工下拉内容
    async getEmployeeListNew () {
      var params = {
        PageIndex: 1,
        PageSize: 10000
      }
      let res = await TreatmentApi.getEmployeeListNew(params)
      console.log('res: ', res)
      if (res.status === 200 && res.data.success) {
        this.queryEmployeeList = res.data.data
        this.arrListDown.employeeList = res.data.data.map(item => {
          return { label: item.name, value: item.id }
        })
      }
    },

    // 获取商保业务类型列表
    async getTreatmentParametersEnableList () {
      let res = await TreatmentApi.getTreatmentParametersEnableList({InsuredTypeId: 9})
        console.log('根据参数类型 获取已启用相关参数列表res: ', res)
        if (res.status === 200 && res.data.success && res.data.data) {
          this.arrListDown.treatmentParametersEnableList = res.data.data.map(item => {
            return { label: item.parameterName, value: item.id }
          })
        }
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        ...this.formData
      }
      params.InsuredTypeId = params.InsuredTypeId ? params.InsuredTypeId : '00000000-0000-0000-0000-000000000000'
      let res = await TreatmentBasicsLinkApi.getList({ ...params })
      console.log('分页查询接口res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.agentCount = res.data.agentCount
        this.tableComone.doneCount = res.data.doneCount
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 表格选择操作
    tableSelectChange (value) {
      console.log(value)
      this.selectedIdArr = value.map((item) => {
        return item.id
      })
    },

    // 导出按钮
    exportBtn () {
      TreatmentBasicsLinkApi.export({
        IdList: this.selectedIdArr.join(','),
        ...this.formData,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }).then(res => {
        console.log(res)
        if (res.data.success) {
          let objectUrl = '/' + res.data.data.replace(/\\/g, '\/')
          const link = document.createElement('a')
          link.download = ''
          link.href = objectUrl
          link.click()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },

    // 显示新增弹窗
    handleShowCreateCommercialWagesModal (actionType, id) {
      this.$refs.CreateCommercialWagesModal.arrListDown.insuredTypeId = this.arrListDown.InsuredTypeId
      this.$refs.CreateCommercialWagesModal.isCreate = id ? false : true
      this.$refs.CreateCommercialWagesModal.formData.linkSort = null
      this.$refs.CreateCommercialWagesModal.arrListDown.linkSort = []
      this.$refs.CreateCommercialWagesModal.show(actionType, id)
      if (id) {
        this.$refs.CreateCommercialWagesModal.getModel(id)
      }
    },

    // 显示完成弹窗
    handleShowCompleteModal (id) {
      this.$refs.CompleteCommercialWagesModal.show(id)
    },

    // 批量导入-显示弹窗
    handleShowTreatmentLinkManageModal () {
      this.$refs.TreatmentLinkManageModal.show()
      this.$refs.TreatmentLinkManageModal.file = null
      this.$refs.TreatmentLinkManageModal.errorData.isError = false
      // this.$refs.TreatmentLinkManageModal.year = this.$moment(this.tableData[0].salaryMonth).format('YYYY')
    },

    // 禁用||启用
    async handleDel (row) {
      console.log('handleDel', row)
      var params = {
        id: row.id,
        linkStatus: row.linkStatus == 0 ? 1 : 0
      }
      let res = await TreatmentBasicsLinkApi.updateLinkStatus(params)
      console.log('禁用||启用res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error(res.data.message)
      }
    },

    // 删除
    async handleDelete (id) {
      this.$Modal.confirm({
        title: '是否确认删除该条信息',
        onOk: async () => {
          let res = await TreatmentBasicsLinkApi.delete({
            id: id
          })
          if (res.data.success) {
            this.$Message.success(res.data.message)
            this.selectedIdArr = []
            this.query()
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 10,
              closable: true
            })
          }
        }
      })
      
    },
    // 是否删除前询问
     isDeleteModal (row) {
      this.$Modal.confirm({
        title: '是否确认删除该条信息',
        onOk: async () => {
          var params = {
            id: row.id
          }
          let res = await TreatmentBasicsLinkApi.delete(params)
          if (res.status === 200 && res.data.success) {
            this.$Message.success(res.data.message)
            this.query()
          } else {
            this.$Message.error(res.data.message)
          }
        }
      })
    },
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
